﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;

namespace Quickuse.Logging.HttpLogger
{
    /// <summary>
    /// HttpLoggerProcessor
    /// </summary>
    internal class HttpLoggerProcessor : IDisposable
    {
        private IHttpLoggerSettings _httpLoggerSettings;
        private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();
        private readonly Thread _outputHttpThread;
        private List<string> logMessages = new List<string>();

        /// <summary>
        /// HttpLoggerProcessor
        /// </summary>
        /// <param name="httpLoggerSettings">httpLoggerSettings</param>
        public HttpLoggerProcessor(IHttpLoggerSettings httpLoggerSettings)
        {
            _httpLoggerSettings = httpLoggerSettings;

            _outputHttpThread = new Thread(ProcessLogQueue)
            {
                IsBackground = true,
                Name = "Http logger queue processing thread"
            };

            _outputHttpThread.Start();

            if (_httpLoggerSettings.ChangeToken != null)
            {
                _httpLoggerSettings.ChangeToken.RegisterChangeCallback(OnConfigurationReload, null);
            }
        }

        /// <summary>
        /// OnConfigurationReload
        /// </summary>
        /// <param name="state"></param>
        public void OnConfigurationReload(object state)
        {
            try
            {
                _httpLoggerSettings = _httpLoggerSettings.Reload();
            }
            catch (Exception ex)
            {
                InternalLog.Error($" while loading configuration changes.{Environment.NewLine}{ex}");
            }
            finally
            {
                // The token will change each time it reloads, so we need to register again.
                if (_httpLoggerSettings?.ChangeToken != null)
                {
                    _httpLoggerSettings.ChangeToken.RegisterChangeCallback(OnConfigurationReload, null);
                }
            }
        }

        /// <summary>
        /// 入队消息
        /// </summary>
        /// <param name="message">message</param>
        /// <param name="logLevel">logLevel</param>
        internal void EnqueueMessage(string message, LogLevel logLevel)
        {
            if (_httpLoggerSettings.IsAsyn)
            {
                _messageQueue.Enqueue(message);
            }
            else
            {
                SendHttp(message);
            }
        }

        /// <summary>
        /// ProcessLogQueue
        /// </summary>
        public void ProcessLogQueue()
        {
            try
            {
                while (true)
                {
                    while (_messageQueue.TryDequeue(out var logMessage))
                    {
                        logMessages.Add(logMessage);
                    }

                    if (logMessages.Count > 0)
                    {
                        SendHttp(logMessages);
                        logMessages.Clear();
                    }

                    Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
                InternalLog.Error($" while ProcessLogQueue.{Environment.NewLine}{ex}");
            }
        }

        /// <summary>
        /// Send Http
        /// </summary>
        /// <param name="message">message</param>
        public void SendHttp(string message)
        {
            try
            {
                if (string.IsNullOrEmpty(message))
                {
                    return;
                }

                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.Timeout = new TimeSpan(0, 0, 0, 0, _httpLoggerSettings.Timeout);

                    using (StringContent httpContent = new StringContent($"[{message}]", Encoding.UTF8, "application/json"))
                    {
                        httpClient.PostAsync(_httpLoggerSettings.HttpServer, httpContent).Wait();
                    }
                }
            }
            catch (Exception ex)
            {
                InternalLog.Error($" while SendHttp.{Environment.NewLine}{ex}");
            }
        }

        /// <summary>
        /// SendHttp
        /// </summary>
        /// <param name="logMessages">logMessages</param>
        public void SendHttp(List<string> logMessages)
        {
            try
            {
                if (string.IsNullOrEmpty(_httpLoggerSettings.HttpServer))
                {
                    return;
                }

                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.Timeout = new TimeSpan(0, 0, 0, 0, _httpLoggerSettings.Timeout);
                    var logMessagepage = logMessages.Paging(100);
                    foreach (var logpage in logMessagepage)
                    {
                        using (StringContent httpContent = new StringContent($"[{string.Join(",", logpage)}]", Encoding.UTF8, "application/json"))
                        {
                            httpClient.PostAsync(_httpLoggerSettings.HttpServer, httpContent).Wait();
                        }
                    }

                    logMessages.Clear();
                }
            }
            catch (Exception ex)
            {
                InternalLog.Error($" while SendHttp.{Environment.NewLine}{ex}");
            }
        }

        public void Dispose()
        {
            try
            {
                _outputHttpThread.Join(_httpLoggerSettings.TaskWaitTime); // with timeout in-case Console is locked by user input
            }
            catch (ThreadStateException) { }
        }
    }
}
